package com.songqi.common.core.validator;

import cn.hutool.core.date.DateUtil;
import com.songqi.common.core.utils.DateUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2024/5/9 19:36
 */
public class DateRegexValidator implements ConstraintValidator<DateRegex, String> {

    private String format = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void initialize(DateRegex constraintAnnotation) {
        format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return isValidDateFormat(value, format);
    }


    private boolean isValidDateFormat(String value, String format) {
        try {
            DateUtils.parseDate(value, format);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }
}
